//
//  ViewModel.swift
//  JonCalculator
//
//  Created by shiyanjun on 2023/1/15.
//

import Foundation

class ViewModel: ObservableObject {
    private var isFinishedTypingNumber: Bool = true
    @Published var displayValue: String = String(0)
    
    private var calculator = CalculatorLogic()
    
    func onButtonPressed(button: CalcButton) {
        switch button {
        case .zero, .one, .two, .three, .four, .five, .six, .seven, .eight, .nine, .decimal:
            numButtonPressed(input: button.rawValue)
        case .add, .subtract, .mutliply, .divide, .equal, .clear, .percent, .negative:
            calcButtonPressed(input: button.rawValue)
        }
    }
    
    // 运算符处理
    func calcButtonPressed(input: String) {
        isFinishedTypingNumber = true
        calculator.setNumber(Double(displayValue)!)
        if let result = calculator.calculate(symbol: input) {
            displayValue = String(result)
        }
    }
    
    // 数字处理
    func numButtonPressed(input: String) {
        if isFinishedTypingNumber {
            displayValue = String(input)
            isFinishedTypingNumber = false
        } else {
            // 小数点处理
            if input == "." {
                let isInt = floor(Double(displayValue)!) == Double(displayValue)
                
                if !isInt {
                    return
                }
            }
            // 拼接数字字符串
            displayValue =  displayValue + String(input)
        }
    }
}
